//
//  UIViewController+Y2Common.m
//  Y2Common
//
//  Created by MacPro on 2021/3/13.
//

#import "UIViewController+Y2Common.h"

@implementation UIViewController (Y2Common)


+ (UIViewController *)y2TopViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    return [UIViewController y2TopViewControllerWithRootViewController:keyWindow.rootViewController];
}

- (UIViewController *)y2TopViewController {
    return [UIViewController y2TopViewControllerWithRootViewController:self];
}


+ (UIViewController *)y2TopViewControllerWithRootViewController:(UIViewController *)rootViewController {
    UIViewController *vc = rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}


//获取第一个parentViewController。如果没有，返回传入VC
+ (UIViewController *)getFirstParentVC:(UIViewController *)vc {
    UIViewController *result = vc;
    while (result.parentViewController != nil) {
        result = result.parentViewController;
    }
    return result;
}

/// 获取系统适配缩放比
+ (CGFloat) y2SystemScale{
    CGFloat scale_screen = [UIScreen mainScreen].scale;
    //不支持iphone3GS的情况
    if (scale_screen==1) {
        scale_screen=2;
    }
    //使用iphone4s的宽度为基准值
    CGFloat baseValue=320;
    int baseScale=2;
    CGRect rx = [UIScreen mainScreen].bounds;
    CGFloat width=rx.size.width;
    CGFloat height=rx.size.height;
    
    //处理iphone6 plus的情况，奇葩的分辨率
    if(scale_screen==3&&((width==414&&height==736)||(width==736&&height==414)))
        scale_screen=2.46;
    //计算缩放比例
    CGFloat v=(height>width?width:height)/baseValue;
    //不支持iphone3GS的情况
    if (v<1) {
        v=1;
    }
    
    v = v*(scale_screen/baseScale);
    //测试6p
    //    v=1.5913125;
    //    scale_screen=2.46;
    //测试6
    //    v=1.171875;
    return 1.0 / scale_screen * v;
}

/// 计算系统适配缩放后大小
+ (CGFloat) y2UISize:(CGFloat) value{
    return value * [UIViewController y2SystemScale];
}

@end
